<script setup lang="ts">
import {
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NForm,
  NFormItem,
  NSelect,
  NDatePicker
} from 'naive-ui'
import { h, onMounted, reactive, ref, computed } from 'vue'
import type { HttpResponsePagination } from '@/utils/http'
import type { DjRecordTableRow } from '@/api/djRecord'
import { sendRequest } from '@/utils/api'
import useFlush from '@/hooks/useFlush'
import { useRouter } from 'vue-router'

import TableView from '@/components/TableView.vue'

interface QueryData {
  code: string | null
  creator: string | null
  endDate: string | null
  startDate: string | null
  statusCode: string | null
  receiver: string | null
  batchCode: string | null
  batchName: string | null
}

const router = useRouter()
useFlush('flushDjRecord', () => queryTableData())

const formData = reactive({} as QueryData)
const statusOptions = [
  { label: '撤销', value: 'A0602' },
  { label: '审批中', value: 'A0603' },
  { label: '拒绝', value: 'A0604' },
  { label: '通过', value: 'A0605' }
]

const formDataDate = computed<any>({
  get() {
    if (!formData.startDate || !formData.endDate) return null
    return [formData.startDate, formData.endDate]
  },
  set(value: string[] | null) {
    if (!value) {
      formData.startDate = null
      formData.endDate = null
    } else {
      formData.startDate = value[0]
      formData.endDate = value[1]
    }
  }
})

const resetFormData = () => {
  formData.code = null
  formData.creator = null
  formData.endDate = null
  formData.startDate = null
  formData.statusCode = null
  formData.receiver = null
  formData.batchCode = null
  formData.batchName = null
}

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

const tableData = ref<DjRecordTableRow[]>([])
const tableLoading = ref(false)
const checkedRowKeys = ref<string[]>([])
const queryTableData = async (flush = false) => {
  checkedRowKeys.value = []
  if (flush) paginationReactive.page = 1
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<DjRecordTableRow>>({
      module: 'djRecord',
      api: 'list',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          ...formData
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}
const columns: DataTableColumns<DjRecordTableRow> = [
  {
    title: '编号',
    key: 'code',
    align: 'center'
  },
  {
    title: '批次编号',
    key: 'batchCode',
    align: 'center'
  },
  {
    title: '批次名称',
    key: 'batchName',
    align: 'center'
  },
  {
    title: '发起人',
    key: 'creator',
    align: 'center'
  },
  {
    title: '督交人',
    key: 'receiver',
    align: 'center'
  },
  {
    title: '物品数量',
    key: 'itemNum',
    align: 'center',
    width: 100
  },
  {
    title: '申请日期',
    key: 'createTime',
    align: 'center'
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 150,
    render: (e) => {
      return h(
        NSpace,
        {
          justify: 'center',
          wrap: false
        },
        {
          default: () => [
            h(
              NButton,
              {
                quaternary: true,
                type: 'primary',
                onClick: () => {
                  router.push({
                    name: 'djRecordDetail',
                    query: {
                      id: e.id,
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              {
                default: () => '详情'
              }
            )
          ]
        }
      )
    }
  }
]

onMounted(() => queryTableData())
</script>

<template>
  <TableView class="dj-record">
    <template #form>
      <NForm
        label-placement="left"
        :show-feedback="false"
        class="dj-record-form"
        @keydown.enter="queryTableData(true)"
      >
        <NFormItem label="编号：">
          <NInput
            v-model:value="formData.code"
            placeholder="请输入编号"
            clearable
          />
        </NFormItem>
        <NFormItem label="批次编号：">
          <NInput
            v-model:value="formData.batchCode"
            placeholder="请输入批次编号"
            clearable
          />
        </NFormItem>
        <NFormItem label="批次名称：">
          <NInput
            v-model:value="formData.batchName"
            placeholder="请输入批次名称"
            clearable
          />
        </NFormItem>
        <NFormItem label="发起人：">
          <NInput
            v-model:value="formData.creator"
            placeholder="请输入发起人"
            clearable
          />
        </NFormItem>
        <NFormItem label="督交人：">
          <NInput
            v-model:value="formData.receiver"
            placeholder="请输入督交人"
            clearable
          />
        </NFormItem>
        <NFormItem
          label="申请日期："
          style="width: 340px"
        >
          <NDatePicker
            v-model:formatted-value="formDataDate"
            date-format="yyyy-MM-dd"
            type="daterange"
            placeholder="请选择申请日期"
            clearable
          />
        </NFormItem>
        <NFormItem label="状态：">
          <NSelect
            v-model:value="formData.statusCode"
            :options="statusOptions"
            placeholder="请选择状态"
            clearable
            style="flex: 1"
          />
        </NFormItem>

        <div style="display: flex; align-items: center">
          <NButton
            :disabled="tableLoading"
            :loading="tableLoading"
            color="#6CB187"
            ghost
            style="min-width: 78rem; margin-right: 20rem"
            @click="queryTableData(true)"
          >
            查询
          </NButton>
          <NButton
            :disabled="tableLoading"
            color="#6CB187"
            ghost
            style="min-width: 78rem"
            @click="resetFormData"
          >
            重置
          </NButton>
        </div>
      </NForm>
    </template>
    <template #table="props">
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        :row-key="(e) => e.formId"
        bordered
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<style scoped lang="scss">
.dj-record {
  padding: 29rem 30rem;
  gap: 25rem 0;
}

.dj-record-form {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  flex-wrap: wrap;
  gap: 10rem 20rem;
}
</style>
